package com.budwk.app.sqfwV2.service.povertyMonitoring;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.sqfw.constants.CommonForAdminConstants;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFamilyPropertyService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.config.ExcelGeneratorConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.excelService.CompleteFlowExcelService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowExcelParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.ExcelRowDataParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.component.povertyMonitoring.FamilyMembersComponent;
import com.budwk.app.sqfwV2.component.povertyMonitoring.QuarterStatisticComponent;
import com.budwk.app.sqfwV2.dto.entity.SqfwFamilyProperty;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.PovertyAlleviationDTO;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.PovertyAlleviationExcelParamForController;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.QuarterStatisticalTableExcelDTO;
import com.budwk.app.sqfwV2.enums.povertyMonitoring.FormingMaterialEnum;
import com.budwk.app.sqfwV2.generator.povertyMonitoring.FamilyAssetsStatisticalTableExcelGenerator;
import com.budwk.app.sqfwV2.generator.povertyMonitoring.FamilyMembersWorksExcelGenerator;
import com.budwk.app.sqfwV2.generator.povertyMonitoring.QuarterStatisticalTableExcelGenerator;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeForAdminUtils;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.security.utils.SecurityUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.IocBean;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;


@IocBean
public class PovertyMonitoringExcelService extends CompleteFlowExcelService {

    private final ThreadLocal<CompleteFlowExcelParamForController> excelParamForControllerThreadLocal = new ThreadLocal<>();
    private static ThreadLocal<Map<String, List<Sqfw_formSummary_new>>> threadLocal = new ThreadLocal();


    @Override
    public List<ResultOfExcelGenerator> createExcel(CompleteFlowExcelParamForController paramForController) {
        String code = (String) paramForController.getCustomerParam().get("code");
        if("3".equals(code)){
            List<ResultOfExcelGenerator> result = new ArrayList<>();
            List<ResultOfExcelGenerator> resultOfExcelGenerators = super.createExcel(paramForController);
            File uploadFile = null;
            List<String> urlList =  resultOfExcelGenerators.stream().map(s->s.getExcelUrl()).collect(Collectors.toList());
            String fileName = "数据集合.zip";
            String filePath = CommonFormOfficeForAdminUtils.getTempFilePath(fileName);
            try {
                uploadFile = new File(filePath);
                CommonFormOfficeForAdminUtils.compressFileList(filePath, urlList);
                SysOss sysOss = CommonFormOfficeForAdminUtils.uploadFile(uploadFile, fileName);
                ResultOfExcelGenerator resultOfExcelGenerator = new ResultOfExcelGenerator();
                resultOfExcelGenerator.setExcelUrl( sysOss.getUrl());
                result.add(resultOfExcelGenerator);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ExecutionException e) {
                throw new RuntimeException(e);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return result;
        }else {
            excelParamForControllerThreadLocal.set(paramForController);
            return  super.createExcel(paramForController);
        }
    }

    @Override
    public AbstractCustomerPdfCreateField getAbstractCustomerField(String jsonStr) {
        return JSONUtil.toBean(jsonStr, PovertyAlleviationDTO.class);
    }

    @Override
    protected void customerPopularExcelGenerateParam(ExcelGenerateParam excelGenerateParam) {
        String fileIdentity = excelGenerateParam.getExcelConfig().getFileIdentity();
        if (String.valueOf(FormingMaterialEnum.A.getCode()).equals(fileIdentity)
                || String.valueOf(FormingMaterialEnum.B.getCode()).equals(fileIdentity)) {
            //县内人员务工，县外人员务工
            FamilyMembersComponent.rowDataBuild(excelGenerateParam, fileIdentity);
        }

        if (String.valueOf(FormingMaterialEnum.D.getCode()).equals(fileIdentity)) {
            PovertyAlleviationExcelParamForController completeFlowExcelParamForController = (PovertyAlleviationExcelParamForController) excelParamForControllerThreadLocal.get();
            excelGenerateParam.getCustomerParamMap().put("year", completeFlowExcelParamForController.getYear());
            excelGenerateParam.getCustomerParamMap().put("quarter", completeFlowExcelParamForController.getQuarter());
            if(completeFlowExcelParamForController.getWebSig()){
                excelGenerateParam.setClientType("web");
            }
            QuarterStatisticalTableExcelDTO quarterStatisticalTableExcelData = QuarterStatisticComponent.createQuarterStatisticalTableExcelData(excelGenerateParam);
            excelGenerateParam.getCustomerParamMap().put("quarterStatisticTableData", quarterStatisticalTableExcelData);
        }

    }

    @Override
    public List<ExcelGeneratorConfig> getExcelGeneratorConfig(List<ExcelCreateConfig> excelCreateConfigList) {
        List<ExcelGeneratorConfig> excelGeneratorConfigs = new ArrayList<>();
        String code = excelCreateConfigList.get(0).getFileIdentity();
        if (String.valueOf(FormingMaterialEnum.A.getCode()).equals(code) || String.valueOf(FormingMaterialEnum.B.getCode()).equals(code)) {
            ExcelGeneratorConfig generatorConfig = new ExcelGeneratorConfig();
            generatorConfig.setExcelGenerator(new FamilyMembersWorksExcelGenerator());
            generatorConfig.setExcelCreateConfig(excelCreateConfigList.get(0));
            excelGeneratorConfigs.add(generatorConfig);
        } else if (String.valueOf(FormingMaterialEnum.C.getCode()).equals(code)) {
            Map<String, List<Sqfw_formSummary_new>> group = threadLocal.get();
            threadLocal.remove();
            SqfwFamilyPropertyService sqfwFamilyPropertyService = NutzIocUtils.getBean(SqfwFamilyPropertyService.class);
            if(CollectionUtil.isEmpty(group)){
                return excelGeneratorConfigs;
            }
            Map<String, Object> param = excelCreateConfigList.get(0).getParam();
            for (String s : group.keySet()) {
                // 需要去查询家庭的财产情况
                Cnd familyPropertyCnd = Cnd.NEW().and(SqfwFamilyProperty::getHouseholdId, "=", s)
                        .and(SqfwFamilyProperty::getYear, "=", param.get("year"))
                        .and(SqfwFamilyProperty::getQuarter, "<=", param.get("quarter"));
                List<SqfwFamilyProperty>  familyPropertys = sqfwFamilyPropertyService.query(familyPropertyCnd);
                ExcelGeneratorConfig generatorConfig = new ExcelGeneratorConfig();
                FamilyAssetsStatisticalTableExcelGenerator excelGenerator = new FamilyAssetsStatisticalTableExcelGenerator(param.get("year")+"年第"+ (String) param.get("quarter"));
                excelGenerator.setSqfwFamilyProperty(familyPropertys);
                excelGenerator.setSqfwFormSummaryNews(group.get(s));
                generatorConfig.setExcelGenerator(excelGenerator);
                generatorConfig.setExcelCreateConfig(excelCreateConfigList.get(0));
                excelGeneratorConfigs.add(generatorConfig);
            }
        } else if (String.valueOf(FormingMaterialEnum.D.getCode()).equals(code)) {
            ExcelGeneratorConfig statisticGeneratorConfig = new ExcelGeneratorConfig();
            statisticGeneratorConfig.setExcelGenerator(new QuarterStatisticalTableExcelGenerator());
            statisticGeneratorConfig.setExcelCreateConfig(excelCreateConfigList.get(0));
            excelGeneratorConfigs.add(statisticGeneratorConfig);
        }

        return excelGeneratorConfigs;
    }


    @Override
    protected List<ExcelRowDataParam> getExcelRowData(CompleteFlowExcelParamForController paramForController) {
        SqfwFormsummaryNewService sqfwFormsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
        SysUserService sysUserService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user sysUser = sysUserService.getUserById(SecurityUtil.getUserId());
        Map<String, Object> customerParam = paramForController.getCustomerParam();
        SqlExpressionGroup sql = Cnd.exps(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.POVERTY_MONITORING.getName())
                .and("to_char(fill_date,'YYYY-MM')", "between", new Object[]{customerParam.get("fillStartDate"), customerParam.get("fillEndDate")})
                .and(Sqfw_formSummary_new::getAuditStatus, "=", "submit")
                .and("param_data->>'personnelStatus'", "=", "1");
        //从户历史进入时需要此编号，不传则默认全部
        if(customerParam.containsKey("houseHoldNumber")&&!ObjectUtil.isEmpty(customerParam.get("houseHoldNumber"))){
            sql.andEquals("param_data->>'houseHoldNumber'", customerParam.get("houseHoldNumber"));
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getProvince())) {
            sql.andEquals(Sqfw_formSummary_new::getProvince, sysUser.getProvince());
        } else if (ObjectUtil.isNotEmpty(customerParam.get("province"))) {
            sql.andEquals(Sqfw_formSummary_new::getProvince, customerParam.get("province"));
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getCity())) {
            sql.andEquals(Sqfw_formSummary_new::getCity, sysUser.getCity());
        } else if (ObjectUtil.isNotEmpty(customerParam.get("city"))){
            sql.andEquals(Sqfw_formSummary_new::getCity, customerParam.get("city"));
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getDistrict())) {
            sql.andEquals(Sqfw_formSummary_new::getDistrict, sysUser.getDistrict());
        } else if (ObjectUtil.isNotEmpty(customerParam.get("district"))){
            sql.andEquals(Sqfw_formSummary_new::getDistrict, customerParam.get("district"));
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getCounty())) {
            sql.andEquals(Sqfw_formSummary_new::getCounty, sysUser.getCounty());
        } else if (ObjectUtil.isNotEmpty(customerParam.get("county"))) {
            sql.andEquals(Sqfw_formSummary_new::getCounty, customerParam.get("county"));
        }
        if (!CommonForAdminConstants.ZHISHU.equals(sysUser.getCommunity())) {
            sql.andEquals(Sqfw_formSummary_new::getCommunity, sysUser.getCommunity());
        } else if (ObjectUtil.isNotEmpty(customerParam.get("community"))) {
            sql.andEquals(Sqfw_formSummary_new::getCommunity, customerParam.get("community"));
        }
        List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query(Cnd.where(sql));
        // 家庭资产
        if (customerParam.get("code").equals("3") && CollectionUtil.isNotEmpty(formSummaryNewList)) {
            Map<String, List<Sqfw_formSummary_new>> group = formSummaryNewList.stream().collect(Collectors.groupingBy(s -> JSONUtil.toBean(s.getParamData(), PovertyAlleviationDTO.class).getHouseHoldId()));
            if (CollectionUtil.isNotEmpty(group)) {
                threadLocal.set(group);
            }
            Map<String, Object> param = paramForController.getExcelCreateConfigList().get(0).getParam();
            param.put("year", customerParam.get("year"));
            param.put("quarter", customerParam.get("quarter"));
        }
        List<ExcelRowDataParam> excelRowDataParamList = transformFormSummaryToExcelRowData(formSummaryNewList);
        if (String.valueOf(FormingMaterialEnum.A.getCode()).equals(customerParam.get("code"))||String.valueOf(FormingMaterialEnum.B.getCode()).equals(customerParam.get("code"))){
            ExcelRowDataParam excelRowDataParam = new ExcelRowDataParam();
            excelRowDataParam.setCustomerParamMap(customerParam);
            excelRowDataParam.setAbstractCustomerPdfCreateField(null);
            if(ObjectUtils.isNotEmpty(excelRowDataParamList)) {
                excelRowDataParamList.add(excelRowDataParam);
            }else{
                excelRowDataParamList = List.of(excelRowDataParam);
            }
        }

        return excelRowDataParamList;
    }


}
